package com.alpha.framework.manager;

import java.util.Iterator;
import java.util.Stack;

import com.alpha.framework.fragment.BaseFragment;
import com.alpha.framework.utils.LogUtils;

import android.app.Activity;
import android.support.v4.app.Fragment;

public class FragmentManager {
	
	private static FragmentManager instance;
	
	/** 管理的fragment stack */
	private static Stack<TagFragment> fragmentStack = new Stack<TagFragment>();
	
	/**
	 * 获得FragmentManager 对象
	 * @return
	 */
	public static FragmentManager getManager() {
		if (instance == null) {
			instance = new FragmentManager();
		}
		return instance;
	}
	
	/** 
	 * 获得当前栈顶Fragment
	 * @return 当前运行的Fragment
	 */
	public Fragment getCurrentFragment(){
		Fragment fragment = null;
		if (!fragmentStack.empty())
			fragment = fragmentStack.lastElement().getFragment();
		return fragment;
	}
	
	/**
	 * 获得当前fragment的类名
	 * @return	当前fragment名字
	 */
	public String getCurrentFragmentName() {
		Fragment fragment = null;
		if (!fragmentStack.empty())
			fragment = fragmentStack.lastElement().getFragment();
		return fragment != null ? fragment.getClass().getSimpleName() : "";
	}
	
	/** 将当前Fragment推入栈中 */
	public void pushFragment(Fragment fragment) {
		if (fragmentStack == null) {
			fragmentStack = new Stack<TagFragment>();
		}
		fragmentStack.add(new TagFragment(fragment.getClass().getName(), fragment));
	}
	
	/** 删除Fragment */
	public void popFragment(String tag){
		Iterator<TagFragment> iterator = fragmentStack.iterator();
		while (iterator.hasNext()) {
			TagFragment next = iterator.next();
			if(next != null && next.getTag().equals(tag)){
				iterator.remove();
			}
		}
	}
	
	/** 删除集合中保存的Fragment */
	public void finishFragment(){
		synchronized (fragmentStack) {
			fragmentStack.clear();
		}
	}
	
	/**
	 * 从保存Fragment 的集合中获取 对应的Fragment
	 * @param tag 集合中对应的 key
	 * @return 
	 */
	public BaseFragment findFragment(String tag){
		LogUtils.i("fragmentStack.size="+fragmentStack.size());
		for(TagFragment item : fragmentStack){
			if(item != null && item.getTag().equals(tag)){
				return (BaseFragment) item.getFragment();
			}
		}
		return null;
	}
	
	
	private class TagFragment{
		private String tag;
		private Fragment fragment;
		public TagFragment(String tag, Fragment fragment) {
			this.tag = tag;
			this.fragment = fragment;
		}
		public String getTag() {
			return tag;
		}
		public Fragment getFragment() {
			return fragment;
		}
	}
}
